//@flow

import {
    FetchDataRequest,
    FetchDataSuccess,
    FetchDataFailed,
    FetchDataCancle,
} from './RefreshActionTypes'

export function fetchDataRequest (identifier) {
    return {
        type: FetchDataRequest,
        identifier,
    }
}

export function fetchDataSuccess (model, identifier) {
    return {
        type: FetchDataSuccess,
        model,
        identifier,
    }
}

export function fetchDataFailed (error, identifier) {
    return {
        type: FetchDataFailed,
        error,
        identifier,
    }
}

export function fetchDataCancle (identifier) {
    return {
        type: FetchDataCancle,
        identifier,
    }
}

function shouldFetchData(state, identifier) {
    const refreshData = state.refreshAble.get(identifier)
    if (!refreshData) {
        return true
    } else if (refreshData.isRefreshing) {
        return false
    }
    return true
}

function fetchData(asyncApi, identifier) {
    return (dispatch, getState) => {
        dispatch(fetchDataRequest(identifier))

        return asyncApi()
            .then((model) => {
                const state = getState()
                if (state.refreshAble.get(identifier)) {
                    dispatch(fetchDataSuccess(model, identifier))
                }
            })
            .catch((error) => {
                const state = getState()
                if (state.refreshAble.get(identifier)) {
                    dispatch(fetchDataFailed(error, identifier))
                }
            })
    }
}

//获取数据
export function fetchDataIfNeeded (asyncApi, identifier) {
    return (dispatch, getState) => {
        if (shouldFetchData(getState(), identifier)) {
            return dispatch(fetchData(asyncApi, identifier))
        } else {
            return Promise.resolve()
        }
    }
}